<template>
  <div class="order-confirm">
    <!-- 顶部标题栏 -->
    <div class="header">
      <div class="back" @click="router.back()">
        <van-icon name="arrow-left" />
      </div>
      <div class="title">确认订单</div>
    </div>

    <!-- 商家信息 -->
    <div class="business-info">
      <div class="business-name">{{ business.businessName }}</div>
      <div class="business-address">{{ business.businessAddress }}</div>
    </div>

    <!-- 商品列表 -->
    <div class="food-list">
      <div class="food-item" v-for="food in cartList" :key="food.foodId">
        <div class="food-name">{{ food.foodName }}</div>
        <div class="food-price">
          <span class="quantity">x{{ food.quantity }}</span>
          <span class="price">¥{{ food.foodPrice * food.quantity }}</span>
        </div>
      </div>
    </div>

    <!-- 配送费 -->
    <div class="delivery-info">
      <div class="delivery-item">
        <span>配送费</span>
        <span>¥{{ business.deliveryPrice }}</span>
      </div>
      <div class="total">
        <span>小计</span>
        <span class="total-price">¥{{ totalPrice }}</span>
      </div>
    </div>

    <!-- 支付方式 -->
    <div class="payment-methods">
      <div class="title">在线支付</div>
      <div class="order-info">
        <div class="business-name">{{ business.businessName }}</div>
        <div class="order-price">¥{{ totalPrice + business.deliveryPrice }}</div>
      </div>
      <div class="payment-list">
        <div class="payment-item" @click="selectedPayment = 'alipay'">
          <div class="payment-left">
            <van-icon name="alipay" color="#1677FF" size="24" />
            <span>支付宝</span>
          </div>
          <van-icon :name="selectedPayment === 'alipay' ? 'checked' : 'circle'" :class="{ active: selectedPayment === 'alipay' }" />
        </div>
        <div class="payment-item" @click="selectedPayment = 'wechat'">
          <div class="payment-left">
            <van-icon name="wechat" color="#07C160" size="24" />
            <span>微信支付</span>
          </div>
          <van-icon :name="selectedPayment === 'wechat' ? 'checked' : 'circle'" :class="{ active: selectedPayment === 'wechat' }" />
        </div>
      </div>
    </div>

    <!-- 确认支付按钮 -->
    <div class="confirm-btn" @click="confirmPayment">
      确认支付
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()

const business = ref({})
const cartList = ref([])
const selectedPayment = ref('alipay') // 默认选择支付宝

// 获取商家信息和购物车列表
onMounted(async () => {
  const businessId = route.query.businessId
  const userInfo = localStorage.getItem('userInfo')
  if (!userInfo) {
    router.push('/login')
    return
  }
  const userId = JSON.parse(userInfo).userId

  try {
    // 获取商家信息
    const businessRes = await request.get(`/business/getBusinessById?businessId=${businessId}`)
    if (businessRes.data.code === 200) {
      business.value = businessRes.data.data
    }

    // 获取购物车列表
    const cartRes = await request.get(`/cart/listCart?userId=${userId}&businessId=${businessId}`)
    if (cartRes.data.code === 200) {
      // 获取商品列表
      const foodRes = await request.get(`/food/listFoodByBusinessId?businessId=${businessId}`)
      if (foodRes.data.code === 200) {
        const foodMap = new Map(
          foodRes.data.data.map(food => [food.foodId, food])
        )

        // 合并购物车和商品信息
        cartList.value = cartRes.data.data.map(item => {
          const food = foodMap.get(item.foodId)
          return {
            ...item,
            foodName: food.foodName,
            foodPrice: food.foodPrice,
            totalPrice: food.foodPrice * item.quantity
          }
        })
      }
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    showToast('获取数据失败')
  }
})

// 计算商品总价
const totalPrice = computed(() => {
  return cartList.value.reduce((total, item) => {
    return total + (item.foodPrice * item.quantity)
  }, 0)
})

// 确认支付
const confirmPayment = async () => {
  try {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    const orderData = {
      userId: userInfo.userId,
      businessId: route.query.businessId,
      orderTotal: totalPrice.value + business.value.deliveryPrice,
      daId: 1,
      paymentMethod: selectedPayment.value,
      orderItems: cartList.value.map(item => ({
        foodId: item.foodId,
        quantity: item.quantity,
        foodPrice: item.foodPrice
      }))
    }

    const res = await request.post('/orders/createOrders', orderData)

    if (res.data.code === 200) {
      showToast('支付成功')
      router.push('/order')
    } else {
      showToast(res.data.message)
    }
  } catch (error) {
    console.error('支付失败:', error)
    showToast('支付失败，请重试')
  }
}
</script>

<style scoped>
.order-confirm {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 140px;
  padding-top: 44px;
}

.header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 44px;
  background: #0097ff;
  color: #fff;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 100;
}

.back {
  font-size: 20px;
  padding: 8px;
  margin-left: -8px;
}

.title {
  flex: 1;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}

.business-info {
  background: #fff;
  padding: 12px 16px;
  font-size: 16px;
  color: #333;
  margin-bottom: 1px;
}

.business-name {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
}

.business-address {
  font-size: 14px;
  color: #666;
}

.food-list {
  background: #fff;
  padding: 0 16px;
}

.food-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f5f5f5;
}

.food-name {
  font-size: 15px;
  color: #333;
  margin-bottom: 4px;
}

.food-price {
  font-size: 15px;
  color: #333;
  font-weight: 500;
}

.quantity {
  font-size: 13px;
  color: #666;
}

.price {
  color: #f60;
  font-weight: bold;
}

.delivery-info {
  background: #fff;
  padding: 16px;
  margin-top: 10px;
}

.delivery-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
  font-size: 14px;
  color: #666;
}

.total {
  margin-bottom: 0;
  padding-top: 12px;
  border-top: 1px solid #f5f5f5;
}

.total-price {
  color: #f60;
  font-weight: bold;
}

.submit-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 50px;
  background: #333;
  display: flex;
  align-items: center;
  padding: 0 16px;
}

.price {
  flex: 1;
  color: #fff;
  font-size: 20px;
  font-weight: bold;
}

.submit-btn {
  width: 100px;
  height: 100%;
  background: #00c755;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
}

.payment-methods {
  margin-top: 12px;
  background: #fff;
  padding: 16px;
}

.payment-methods .title {
  font-size: 16px;
  color: #333;
  margin-bottom: 12px;
}

.order-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.order-info .business-name {
  font-size: 14px;
  color: #666;
}

.order-info .order-price {
  font-size: 16px;
  color: #f60;
  font-weight: bold;
}

.payment-list {
  margin-top: 12px;
}

.payment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  cursor: pointer;
}

.payment-left {
  display: flex;
  align-items: center;
}

.payment-left img {
  width: 24px;
  height: 24px;
  margin-right: 8px;
}

.payment-left span {
  font-size: 14px;
  color: #333;
}

.van-icon {
  font-size: 20px;
  color: #ddd;
}

.van-icon.active {
  color: #00c755;
}

.confirm-btn {
  position: fixed;
  left: 16px;
  right: 16px;
  bottom: 80px;
  height: 44px;
  background: #00c755;
  color: #fff;
  border-radius: 22px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
}
</style> 